let currentLevel = parseInt(localStorage.getItem('currentLevel')) || 1;
const maxLevel = 10;

// 上传头像功能
document.getElementById('avatar-upload').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatar-preview').src = e.target.result;
            localStorage.setItem('avatar', e.target.result); // 保存头像
        };
        reader.readAsDataURL(file);
    }
});

// 加载保存的头像
const savedAvatar = localStorage.getItem('avatar');
if (savedAvatar) {
    document.getElementById('avatar-preview').src = savedAvatar;
}

// 开始游戏
document.getElementById('start-game').addEventListener('click', function() {
    startLevel(currentLevel);
});

// 弹窗相关元素
const modal = document.getElementById('game-modal');
const questionElement = document.getElementById('question');
const answerInput = document.getElementById('answer-input');
const submitButton = document.getElementById('submit-answer');
const resultMessage = document.getElementById('result-message');

// 提交答案
submitButton.addEventListener('click', function() {
    const userAnswer = parseInt(answerInput.value);
    if (userAnswer === currentAnswer) {
        resultMessage.textContent = '答对了！你真棒！';
        currentLevel++;
        if (currentLevel > maxLevel) {
            alert('恭喜你，通关了！');
            currentLevel = 1; // 重置关卡
        }
        localStorage.setItem('currentLevel', currentLevel); // 保存当前关卡
        document.getElementById('current-level').textContent = currentLevel;
        setTimeout(() => {
            modal.style.display = 'none';
            startLevel(currentLevel); // 进入下一关
        }, 1000);
    } else {
        resultMessage.textContent = '再试一次吧！';
    }
});

let currentAnswer;

// 关卡逻辑
function startLevel(level) {
    const num1 = Math.floor(Math.random() * level * 2) + 1;
    const num2 = Math.floor(Math.random() * level * 2) + 1;
    const operations = ['+', '-', '*'];
    const operation = operations[Math.floor(Math.random() * operations.length)];

    switch (operation) {
        case '+':
            currentAnswer = num1 + num2;
            break;
        case '-':
            currentAnswer = num1 - num2;
            break;
        case '*':
            currentAnswer = num1 * num2;
            break;
    }

    questionElement.textContent = `第${level}关：${num1} ${operation} ${num2} = ?`;
    answerInput.value = '';
    resultMessage.textContent = '';
    modal.style.display = 'flex';
}